import {commons} from "@/utils/commons"
import {sendTextCode} from "@/service/api";
import {ref} from "vue";

export default function () {
    let send = ref(false)//验证码发送状态
    let times = ref(60)//倒计时时长
    // 发送验证码
    function doSend(mobile: string) {
        let judge = testMobile(mobile)
        if (judge) {
            if (!send.value) {
                sendTextCode({mobile: mobile}).then((res: any) => {
                    commons.showToast('已发送至' + mobile + '~')
                    send.value = true
                    let timer = setInterval(() => {
                        if (times.value > 0 && times.value <= 60) {
                            times.value--
                        } else {
                            send.value = false
                            times.value = 60
                            clearInterval(timer)
                        }
                    }, 1000)
                })
            } else {
                return commons.showToast(times.value + 's内不能重复发送！')
            }
        } else {
            return commons.showToast('请填写正确的手机号!')
        }
    }

    function testMobile(mobile: string) {
        return /^1([3-9]\d|4[5-9]|6[1-2,4-7]|7[0-8])\d{8}$/.test(mobile)
    }

    return {
        doSend,
        times
    }
}